package org.feng.config;

import cn.dev33.satoken.stp.StpInterface;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.feng.entity.Menu;
import org.feng.entity.Role;
import org.feng.entity.User;
import org.feng.feign.MenuFeign;
import org.feng.feign.RoleFeign;
import org.feng.feign.UserFeign;
import org.feng.utils.ResponseUtil;
import org.feng.utils.UserUtil;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author feng
 * @Date 2022/3/8 15:23
 * @Description TODO
 */
@Component
@AllArgsConstructor
@Slf4j
public class SaTokenAnnotationAuth implements StpInterface {

    private final UserFeign userFeign;
    private final MenuFeign menuFeign;
    private final RoleFeign roleFeign;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        log.info("执行获取用户权限；userId:{}",loginId);
        User user = ResponseUtil.checkResponse(userFeign.getById(UserUtil.getUserId()));
        List<Menu> list = ResponseUtil.checkResponse(menuFeign.getButtons(user.getRoleId()));
        return list.stream().map(menu -> {
            return menu.getCode().replace("_", ":");
        }).collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        log.info("执行获取用户角色；userId:{}",loginId);
        User user = ResponseUtil.checkResponse(userFeign.getById(UserUtil.getUserId()));
        Role role = ResponseUtil.checkResponse(roleFeign.getById(user.getRoleId()));
        return Collections.singletonList(role.getName());
    }
}
